package me.chan.netty.practice;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.concurrent.Future;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.Charset;
import java.util.Scanner;

@Slf4j
public class EchoClient {

    static final String SERVER_HOST = "127.0.0.1";
    static final int SERVER_PORT = 8080;

    public static void main(String[] args) throws InterruptedException {

        Bootstrap bootstrap = new Bootstrap();
        NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        Channel channel = bootstrap.group(eventLoopGroup)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline()
                                .addLast(new LoggingHandler(LogLevel.DEBUG))
                                .addLast(new StringEncoder())
                                .addLast(new ChannelInboundHandlerAdapter() {
                                    @Override
                                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                        ByteBuf buf = (ByteBuf) msg;
                                        log.debug("receive from server:{}", buf.toString(Charset.forName("UTF-8")));
                                    }
                                });
                    }
                }).connect(SERVER_HOST, SERVER_PORT)
                .sync().channel();


        new Thread(() -> {
            while (true) {
                Scanner scanner = new Scanner(System.in);
                String line = scanner.nextLine();
                if ("q".equalsIgnoreCase(line)
                        || "quit".equalsIgnoreCase(line)
                        || "q".equalsIgnoreCase(line.trim())
                        || "quit".equalsIgnoreCase(line.trim())) {
                    channel.close();
                    break;
                }

                channel.writeAndFlush(line);
            }
        }, "scanner-thread").start();

        channel.closeFuture().addListener((Future<Void> f) ->
                eventLoopGroup.shutdownGracefully()
        );
    }
}
